import axios from "axios";
import Qs from "qs";
import { getToken } from "@/utils/auth";
import store from "@/store";
import router from "../router";

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl;
    this.queue = {};
  }
  getInsideConfig(method) {
    var token = getToken();
    if (!token) token = "";
    var headers = {
      // "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": 'Bearer ' + token
    };
    const config = {
      baseURL: this.baseUrl,
      headers,
      params: {
        token
      },
      transformRequest: [
        function (data) {
          if (method === "post" || method === "put") {
            return Qs.stringify(data);
          } else {
            return data;
          }
        }
      ]
    };
    return config;
  }
  destroy(url) {
    delete this.queue[url];
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(
      config => {
        // 添加全局的loading...
        if (!Object.keys(this.queue).length) {
          // Spin.show() // 不建议开启，因为界面不友好
        }
        if (config.method === "get") {
          //处理 get token
          if (config.data) config.data.token = config.params.token;
          var params = Object.assign(config.params, config.data);
          config.params = params;
        }
        this.queue[url] = true;
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        if (res.data == null) {
          this.$notify({
            title: "提醒",
            message: "无请求结果",
            type: 'warning'
          });
          return Promise.reject("无请求结果");
        }
        if (res && res.data && !res.data.success) {
          if (
            !!res.data.statusCode && res.data.statusCode == 401 &&
            url != "/login"
          ) {
            this.confirm('你的账号在别处登录,请重新登录',"提醒",{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              store.dispatch("user/resetToken").then(() => {
                location.reload(); // 为了重新实例化vue-router对象 避免bug
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          } else if (!!res.data.statusCode && res.data.statusCode == 403) {
            //跳转 500
            //error_401
            router.replace({ path: "/404" });
          } else {

            // var message

            if (!!res.data.data.message && res.data.status != 200) {
              this.$notify({
                title: "提醒",
                message: res.data.data.message,
                type: 'warning'
              });
            } else if (!!res.data.message && res.data.status != 200) {
              this.$notify({
                title: "提醒",
                message: res.data.message,
                type: 'warning'
              });
            }
          }
        }

        this.destroy(url);
        const { data } = res;
        return data;
      },
      error => {
        this.destroy(url);
        this.$notify({
          title: "提醒",
          message: error,
          type: 'warning'
        });

        Spin.hide();
        // addErrorLog(error.response)
        return Promise.reject(error);
      }
    );
  }
  request(options) {
    var method = options.method.toLowerCase();
    const instance = axios.create();
    options = Object.assign(this.getInsideConfig(method), options);
    this.interceptors(instance, options.url);
    return instance(options);
  }
}
export default HttpRequest;
